<?
require("../../common/init.php");
include(ROOT."common/class_image_resize.php");
require(ROOT."common/image_zoom.php");
require("author.php");
require("upfile.php");

$gee=$product; // gee, 意为赶车时候喊的"驾", 此处用来表示次页面的主角对象 gee=role object
$cate=$product_category; // cate = category, 分类
$cateid=0;
$gee_tags = $tags;
$gee_tag_list = $tag_list;

$filter="";
if(isset($_GET["filter"]))$filter=clean($_GET["filter"]);
if(isset($_POST["filter"]))$filter=clean($_POST["filter"]);

if(!empty($filter)) {
	$title=ROOT_PRODUCT_OUT_OF_STOCK;
}
else {
	$title=ROOT_PRODUCT_LIST;
}
$url='product';

$s=isset($_GET["s"])?clean($_GET["s"]):''; // search
$t=isset($_GET["t"])?clean($_GET["t"]):''; // search
$do=isset($_GET["do"])?clean($_GET["do"]):'view'; // 操作: 查看/编辑/删除
$action=isset($_POST["action"])?clean($_POST["action"]):''; // 数据库操作: CURD
$page=1; if(isset($_GET["page"]))if(is_numeric($_GET["page"]))$page=$_GET["page"]; // 当前页码 current page
$id=isset($_GET["id"])?clean($_GET["id"]):0;

// sql action / sql 动作
switch ($action){
	case "update": sql_update(); break;
	case "add": sql_insert(); break;
    case "deletes": sql_deletes(); break;
    case "is_enable": sql_is_enable(); break;
    case "dis_enable": sql_dis_enable(); break;
    case "tags_add": sql_tags_add(); break;
}

$tag_list_info = $gee_tags->get_rows(1024);

if($id==0){
	$order='seq_no';
	$where=array();
	if($filter!='') {
		$where[]=array('name'=>'stock','name2'=>'safety_stock','opn'=>'<', 'and'=>'and');
	}
	if($s!='') {
		$where[]=array('name'=>'name_en','val'=>$s,'opn'=>'like', 'and'=>'and', 'start'=>'(');
		$where[]=array('name'=>'name_sc','val'=>$s,'opn'=>'like', 'and'=>'or');
		$where[]=array('name'=>'name_tc','val'=>$s,'opn'=>'like', 'and'=>'or');
		$where[]=array('name'=>'name_ot','val'=>$s,'opn'=>'like', 'and'=>'or');
		$where[]=array('name'=>'sku','val'=>$s,'opn'=>'like', 'and'=>'or', 'end'=>')');
	}
    if($t!=''){
        $where_t = array();
        $tag_list_arr = array();
        $where_t[] = array('name'=>'name_'.$lang, 'val'=>$t, 'opn'=>'like', 'and'=>'and');
        $tags_info = $gee_tags->get_rows_advanced(1024, $where_t);
        //pre($tags_info);
        foreach($tags_info as $val_t){
            $where_d = array();
            $where_d[] = array('name'=>'tag_id', 'val'=>$val_t['id'], 'opn'=>'=', 'and'=>'and');
            $where_d[] = array('name'=>'tags_table', 'val'=>1, 'opn'=>'=', 'and'=>'and');

            $tag_list_info_i = $gee_tag_list->get_rows_advanced(1024, $where_d);
            foreach($tag_list_info_i as $val_d){
                $tag_list_arr[] = $val_d['p_id'];
            }
            unset($where_d);
//            unset($val_t);
        }
        $where[] = array('name'=>'id', 'val'=>$tag_list_arr, 'opn'=>'in', 'and'=>'and');
    }

	$total_products=$gee->count_rows();
	$pages=$gee->count_pages($where);
	$info=$gee->get_page($page,$where,$order);
}
else{
    $info=$gee->get_row($id);
    $where = array();
    $where[]=array('name'=>'p_id','val'=>$id);
    $where[]=array('name'=>'tags_table','val'=>1);
    $tag = $gee_tag_list->get_rows_advanced(1024, $where);

//    $tag = $gee_tag_list->get_rows(1024, 'p_id', $id);
    $arr_tag = array();
    for($i = 0; $i < count($tag); $i++){
        $tag_info = $gee_tags->get_row($tag[$i]['tag_id']);
        $tag[$i]['tag_name'] = $tag_info['name_'.$lang];
        $arr_tag[] = $tag[$i]['tag_id'];
    }
    $str_tag = implode(',', $arr_tag);
}


function add()
{
	global $h, $url;
	$row = array(
	);
	echo $h->form($url.'.php', 1, '');
	show_box($row, true, true);
	echo $h->hidden('action', 'add');
	echo $h->former();
}
function update($info)
{
	global $gee, $h, $url, $id;
	if($id=="") 
	{
		echo "Invali argument!!!";
		exit;
	}
	echo $h->form($url.'.php', 1, '');
  	show_box($info, true, false);
	echo $h->hidden('action', 'update');
	echo $h->former();
}
function delete($id)
{
	global $gee,$url, $page, $cateid, $gee_tags, $gee_tag_list;
    $tag_list_arr = $gee_tag_list->get_rows(1024, 'p_id', $id);
	$upload_folder=ROOT.'upload/';
	$info=$gee->get_row($id);
	$old_pic_small=$upload_folder.$info['small_pic'];
	$old_pic_large=$upload_folder.$info['large_pic'];
	if($gee->delete($id)){
        foreach($tag_list_arr as $key => $val){
                $gee_tag_list->delete($val['id']);
                $count = $gee_tags->get_row($val['tag_id']);
                $tag_arr = array('count' => $count['count'] - 1);
                $gee_tags->update($tag_arr, 'id', $val['tag_id']);
        }
		@unlink($old_pic_small);
		@unlink($old_pic_large);
		wheel("$url-$cateid-p$page.html");
	}
}
function flip($id,$where='is_enabled')
{
	global $gee, $url, $page, $cateid, $filter;
	if($gee->flip($id,$where)) echo "<script>location='$url-$cateid-p$page".(($filter=="")?"":"-fout_of_stock").".html';</script>";
}	
function show_info($info)
{
	global $id;
	if($id==0)
	{
  	show_boxes($info);
	}
	else
	{
		show_box($info, false);
	}
}
function sql_insert()
{
	global $gee,$url,$arrlang, $cross_sell, $gee_tags, $gee_tag_list;
	$is_enabled=isset($_POST["is_enabled"])?$_POST["is_enabled"]:0;
	$is_virtual=isset($_POST["is_virtual"])?$_POST["is_virtual"]:0;
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);

	$arr=array(
		'seq_no'=>$_POST["seq_no"],
		'price'=>$_POST["price"],
		'weight'=>$_POST["weight"],
		'unit'=>$_POST["unit"],
		'stock'=>$_POST["stock"],
		'safety_stock'=>$_POST["safety_stock"],
		'sku'=>$_POST["sku"],
		'category_id'=>$_POST["category_id"],
		'is_enabled'=>$is_enabled,
		'is_virtual'=>$is_virtual,
	);
	foreach($arrlang as $val){ // 加载所有启用的分语言的字段, add all fields that marked by languages
		$arr['name_'.$val['code']]=$_POST['name_'.$val['code']];
		$arr['description_'.$val['code']]=$_POST['description_'.$val['code']];
		$arr['feature_'.$val['code']]=$_POST['feature_'.$val['code']];
		$arr['spec_'.$val['code']]=$_POST['spec_'.$val['code']];
		//$arr['other1_'.$val['code']]=$_POST['other1_'.$val['code']];
    }
	if($_FILES["cpic"]["size"] > 0) {
		$pic=upfile($_FILES["cpic"]);
		$upload_folder='../../upload/';
		$large_pic=substr($pic,0,strlen($pic)-4).'-large.jpg';
		//$image_resize=new Image_resize($upload_folder.$pic,PRODUCT_LARGE_PIC_WIDTH,PRODUCT_LARGE_PIC_HEIGHT,0,$upload_folder.$large_pic);
		image_zoom($upload_folder.$pic, $upload_folder.$large_pic,PRODUCT_LARGE_PIC_WIDTH,PRODUCT_LARGE_PIC_HEIGHT,'#ffffff');
		//$image_resize=new Image_resize($upload_folder.$pic,PRODUCT_SMALL_PIC_WIDTH,PRODUCT_SMALL_PIC_HEIGHT,1,$upload_folder.$pic);
		image_zoom($upload_folder.$pic, $upload_folder.$pic,PRODUCT_SMALL_PIC_WIDTH,PRODUCT_SMALL_PIC_HEIGHT,'#ffffff');
		$arr['small_pic']=$pic;
		$arr['large_pic']=$large_pic;
	}
	//pre($arr); exit;
	if($gee->insert($arr)){
		$id=$gee->get_last_insert_id();
        foreach($tag_list_str_2_arr as $key => $val){
            if($val){
                $tag_insert_arr=array(
                    'tag_id' => $val,
                    'p_id'=>$id,
                    'tags_table' => 1,
                    'user_id' => decrypt($_COOKIE['userid'])
                );
                $gee_tag_list->insert($tag_insert_arr);
                $count = $gee_tags->get_row($val);
                $tag_arr = array('count' => $count['count'] + 1);
                $gee_tags->update($tag_arr, 'id', $val);
                unset($tag_insert_arr);
                unset($tag_arr);
            }
        }
		// cross sell begin
		$tem=$_POST["cross_sell"];
		$arr_tem=explode(',',$tem);
		$data=array();
		foreach($arr_tem as $val){
			$data[]=array(
				'product_id'=>$id,
				'cross_product_id'=>trim($val),
			);
		}
		foreach($data as $val){
			$cross_sell->insert($val);
		}

		// 循环交叉促销, 已造成混淆, 废止
		// cross sell begin
		// $tem=$_POST["cross_sell"];
		// $arr_tem=explode(',',$tem);
		// $arr_tem[]=$id;
		// $arr=array();
		// foreach($arr_tem as $val){
		// 	foreach($arr_tem as $val2){
		// 		if($val!=$val2)
		// 		$arr[]=array(
		// 			'product_id'=>$val,
		// 			'cross_product_id'=>trim($val2),
		// 		);
		// 	}
		// }
		// foreach($arr as $data){ 
		// 	$cross_sell->insert($data);
		// }
		// cross sell end
		yell(ROOT_ADD_SUCCESS,$url.'.php');
	}
}
function sql_update()
{
	global $gee, $url, $arrlang, $cross_sell, $gee_tags, $gee_tag_list;
	$delete_old_pic=0;
	$upload_folder=ROOT.'upload/';
	$id=$_POST["id"];
	$page=$_POST["page"];

	$is_enabled=isset($_POST["is_enabled"])?$_POST["is_enabled"]:0;
	$is_virtual=isset($_POST["is_virtual"])?$_POST["is_virtual"]:0;
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);
    $where = array();
    $where[]=array('name'=>'p_id','val'=>$id);
    $where[]=array('name'=>'tags_table','val'=>1);
    $tag_list_arr = $gee_tag_list->get_rows_advanced(1024, $where);
//    $tag_list_arr = $gee_tag_list->get_rows(1024, 'p_id', $id);
    $tag_same = array();
    foreach($tag_list_arr as $key => $val){
        if(in_array($val['tag_id'], $tag_list_str_2_arr)){
            $tag_same[] = $val['tag_id'];
        }
    }

	$arr=array(
		'seq_no'=>$_POST["seq_no"],
		'price'=>$_POST["price"],
		'weight'=>$_POST["weight"],
		'unit'=>$_POST["unit"],
		'stock'=>$_POST["stock"],
		'safety_stock'=>$_POST["safety_stock"],
		'sku'=>$_POST["sku"],
		'category_id'=>$_POST["category_id"],
		'is_enabled'=>$is_enabled,
		'is_virtual'=>$is_virtual,
	);
	foreach($arrlang as $val){ // 加载所有启用的分语言的字段, add all fields that marked by languages
		$arr['name_'.$val['code']]=$_POST['name_'.$val['code']];
		$arr['description_'.$val['code']]=$_POST['description_'.$val['code']];
		$arr['feature_'.$val['code']]=$_POST['feature_'.$val['code']];
		$arr['spec_'.$val['code']]=$_POST['spec_'.$val['code']];
		//$arr['other1_'.$val['code']]=$_POST['other1_'.$val['code']];
    }
	if($_FILES["cpic"]["size"]>0) { // 更新图片
		$info=$gee->get_row($id);
		$old_pic_small=$upload_folder.$info['small_pic'];
		$old_pic_large=$upload_folder.$info['large_pic'];
		$delete_old_pic=1;

		$pic=upfile($_FILES["cpic"]);
		$large_pic=substr($pic,0,strlen($pic)-4).'-large.jpg';
		//$image_resize=new Image_resize($upload_folder.$pic,PRODUCT_LARGE_PIC_WIDTH,PRODUCT_LARGE_PIC_HEIGHT,0,$upload_folder.$large_pic);
		image_zoom($upload_folder.$pic, $upload_folder.$large_pic,PRODUCT_LARGE_PIC_WIDTH,PRODUCT_LARGE_PIC_HEIGHT,'#ffffff');
		//$image_resize=new Image_resize($upload_folder.$pic,PRODUCT_SMALL_PIC_WIDTH,PRODUCT_SMALL_PIC_HEIGHT,1,$upload_folder.$pic);
		image_zoom($upload_folder.$pic, $upload_folder.$pic,PRODUCT_SMALL_PIC_WIDTH,PRODUCT_SMALL_PIC_HEIGHT,'#ffffff');
		$arr['small_pic']=$pic;
		$arr['large_pic']=$large_pic;
	}
	// cross sell begin
	$tem=$_POST["cross_sell"];
	// 删除旧数据  delete old data
	$cross_sell->delete($id, 'product_id');

	$arr_tem=explode(',',$tem);
	$data=array();
	foreach($arr_tem as $val){
		$data[]=array(
			'product_id'=>$id,
			'cross_product_id'=>trim($val),
		);
	}
	foreach($data as $val){
		$cross_sell->insert($val);
	}
	// cross sell end
    foreach($tag_list_arr as $key => $val){
        if(!in_array($val['tag_id'], $tag_same)){
            $gee_tag_list->delete($val['id']);
            $count = $gee_tags->get_row($val['tag_id']);
            $tag_arr = array('count' => $count['count'] - 1);
            $gee_tags->update($tag_arr, 'id', $val['tag_id']);
            unset($tag_arr);
        }
    }
    foreach($tag_list_str_2_arr as $key => $val){
        if(!in_array($val, $tag_same)){
            $tag_insert_arr=array(
                'tag_id' => $val,
                'p_id'=>$id,
                'tags_table' => 1,
                'user_id' => decrypt($_COOKIE['userid'])
            );
            $gee_tag_list->insert($tag_insert_arr);
            $count = $gee_tags->get_row($val);
            $tag_arr = array('count' => $count['count'] + 1);
            $gee_tags->update($tag_arr, 'id', $val);
            unset($tag_insert_arr);
            unset($tag_arr);
        }
    }
	if($gee->update($arr, 'id', $id ) ) {

		if($delete_old_pic){
			@unlink($old_pic_small);
			@unlink($old_pic_large);
		}
		yell(ROOT_UPDATE_SUCCESS,$url.'.php?'.(($_POST['filter']!="")?"filter=out_of_stock":"").'&page='.$page);
	}
	else wheel($url.'.php?'.(($_POST['filter']!="")?"filter=out_of_stock":"").'&page='.$page);
}

function sql_deletes(){
    global $gee,$page,$url, $gee_tag_list, $gee_tags;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    if(count($all)>0){
        foreach($all as $a){
//            $arrdelete[]=$a;
            $tag_list_arr = $gee_tag_list->get_rows(1024, 'p_id', $a);
            $upload_folder=ROOT.'upload/';
            $info=$gee->get_row($a);
            $old_pic_small=$upload_folder.$info['small_pic'];
            $old_pic_large=$upload_folder.$info['large_pic'];
            if($gee->delete($a)){
                foreach($tag_list_arr as $key => $val){
                    $gee_tag_list->delete($val['id']);
                    $count = $gee_tags->get_row($val['tag_id']);
                    $tag_arr = array('count' => $count['count'] - 1);
                    $gee_tags->update($tag_arr, 'id', $val['tag_id']);
                }
                @unlink($old_pic_small);
                @unlink($old_pic_large);
            }
        }
    }
//    if($gee->delete_rows($arrdelete))
        wheel($url.'.php?filter='.$filter.'&s='.$s.'&page='.$page);
}

function sql_is_enable(){
    global $gee,$page,$url;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    if(count($all)>0){
        foreach($all as $a){
            $arr = array('is_enabled'=>1);
            $gee->update($arr, 'id', $a);
            unset($arr);
        }
    }
}

function sql_dis_enable(){
    global $gee,$page,$url;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    if(count($all)>0){
        foreach($all as $a){
            $arr = array('is_enabled'=>0);
            $gee->update($arr, 'id', $a);
            unset($arr);
        }
    }
}

function sql_tags_add(){
    global $gee,$page,$url, $gee_tag_list, $gee_tags;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);
    if(count($all)>0){
        foreach($all as $a){
            $where = array();
            $where[]=array('name'=>'p_id','val'=>$a);
            $where[]=array('name'=>'tags_table','val'=>1);
            $tag_list_arr = $gee_tag_list->get_rows_advanced(1024, $where);
            $tag_same = array();
            foreach($tag_list_arr as $key => $val){
                if(in_array($val['tag_id'], $tag_list_str_2_arr)){
                    $tag_same[] = $val['tag_id'];
                }
            }
            foreach($tag_list_str_2_arr as $key => $val){
                if(!in_array($val, $tag_same)){
                    $tag_insert_arr=array(
                        'tag_id' => $val,
                        'p_id'=>$a,
                        'tags_table' => 1,
                        'user_id' => decrypt($_COOKIE['userid'])
                    );
                    $gee_tag_list->insert($tag_insert_arr);
                    $count = $gee_tags->get_row($val);
                    $tag_arr = array('count' => $count['count'] + 1);
                    $gee_tags->update($tag_arr, 'id', $val);
                    unset($tag_insert_arr);
                    unset($tag_arr);
                }
            }
            unset($where);
            unset($tag_same);
        }
    }
}
// view 加载视图
require ROOTVIEW.$url.'.php';


// end product.php